'use client'

import { useState, useEffect } from 'react'
import { Plus, Trash2, Edit3, Check, X, RefreshCw, AlertCircle, Filter } from 'lucide-react'
import {
  DndContext, 
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  DragEndEvent,
} from '@dnd-kit/core'
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from '@dnd-kit/sortable'
import { 
  Todo, 
  TodoCreate, 
  TodoUpdate, 
  TodoStatus, 
  TodoPriority,
  TodoReorderItem,
  STATUS_LABELS,
  PRIORITY_LABELS,
  STATUS_COLORS,
  PRIORITY_COLORS,
  TodoStats
} from '../types/todo'
import { todoApi } from '../services/todoApi'
import SortableTodoItem from './SortableTodoItem'

export default function TodoList() {
  // 状态管理
  const [todos, setTodos] = useState<Todo[]>([])
  const [stats, setStats] = useState<TodoStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [inputValue, setInputValue] = useState('')
  const [inputDescription, setInputDescription] = useState('')
  const [inputPriority, setInputPriority] = useState<TodoPriority>(TodoPriority.MEDIUM)
  const [editingId, setEditingId] = useState<number | null>(null)
  const [editingData, setEditingData] = useState<Partial<Todo>>({})
  const [filterStatus, setFilterStatus] = useState<TodoStatus | 'all'>('all')
  const [filterPriority, setFilterPriority] = useState<TodoPriority | 'all'>('all')
  const [isDragging, setIsDragging] = useState(false)

  // 拖拽传感器配置
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates,
    })
  )
  const loadTodos = async () => {
    try {
      setLoading(true)
      setError(null)
      
      const params: any = {}
      if (filterStatus !== 'all') params.status = filterStatus
      if (filterPriority !== 'all') params.priority = filterPriority
      
      const response = await todoApi.getAll(params)
      if (response.success) {
        setTodos(response.data)
      } else {
        setError(response.message || '获取待办事项失败')
      }
    } catch (err) {
      setError('网络错误，请检查后端服务是否启动')
      console.error('加载待办事项失败:', err)
    } finally {
      setLoading(false)
    }
  }

  // 加载统计信息
  const loadStats = async () => {
    try {
      const response = await todoApi.getStats()
      if (response.success && response.data) {
        setStats(response.data)
      }
    } catch (err) {
      console.error('加载统计信息失败:', err)
    }
  }

  // 初始化加载
  useEffect(() => {
    loadTodos()
    loadStats()
  }, [filterStatus, filterPriority])

  // 添加任务
  const addTodo = async () => {
    if (inputValue.trim() === '') return
    
    try {
      const newTodo: TodoCreate = {
        title: inputValue.trim(),
        description: inputDescription.trim() || undefined,
        priority: inputPriority,
        status: TodoStatus.PENDING
      }
      
      const response = await todoApi.create(newTodo)
      if (response.success) {
        setInputValue('')
        setInputDescription('')
        setInputPriority(TodoPriority.MEDIUM)
        await loadTodos()
        await loadStats()
      } else {
        setError(response.message || '创建待办事项失败')
      }
    } catch (err) {
      setError('网络错误，请检查后端服务')
      console.error('创建待办事项失败:', err)
    }
  }

  // 删除任务
  const deleteTodo = async (id: number) => {
    if (!confirm('确定要删除这个待办事项吗？')) return
    
    try {
      const response = await todoApi.delete(id)
      if (response.success) {
        await loadTodos()
        await loadStats()
      } else {
        setError(response.message || '删除待办事项失败')
      }
    } catch (err) {
      setError('网络错误，请检查后端服务')
      console.error('删除待办事项失败:', err)
    }
  }

  // 开始编辑任务
  const startEdit = (todo: Todo) => {
    setEditingId(todo.id)
    setEditingData({
      title: todo.title,
      description: todo.description,
      status: todo.status,
      priority: todo.priority
    })
  }

  // 保存编辑
  const saveEdit = async () => {
    if (!editingId || !editingData.title?.trim()) return
    
    try {
      const updateData: TodoUpdate = {
        title: editingData.title?.trim(),
        description: editingData.description?.trim() || undefined,
        status: editingData.status,
        priority: editingData.priority
      }
      
      const response = await todoApi.update(editingId, updateData)
      if (response.success) {
        setEditingId(null)
        setEditingData({})
        await loadTodos()
        await loadStats()
      } else {
        setError(response.message || '更新待办事项失败')
      }
    } catch (err) {
      setError('网络错误，请检查后端服务')
      console.error('更新待办事项失败:', err)
    }
  }

  // 取消编辑
  const cancelEdit = () => {
    setEditingId(null)
    setEditingData({})
  }

  // 切换任务完成状态
  const toggleComplete = async (todo: Todo) => {
    const newStatus = todo.status === TodoStatus.COMPLETED 
      ? TodoStatus.PENDING 
      : TodoStatus.COMPLETED
    
    try {
      const response = await todoApi.update(todo.id, { status: newStatus })
      if (response.success) {
        await loadTodos()
        await loadStats()
      } else {
        setError(response.message || '更新状态失败')
      }
    } catch (err) {
      setError('网络错误，请检查后端服务')
      console.error('更新状态失败:', err)
    }
  }

  // 重置数据
  const resetData = async () => {
    if (!confirm('确定要重置所有数据吗？这将删除当前所有待办事项并重新生成示例数据。')) return
    
    try {
      setLoading(true)
      const response = await todoApi.reset()
      if (response.success) {
        await loadTodos()
        await loadStats()
      } else {
        setError(response.message || '重置数据失败')
      }
    } catch (err) {
      setError('网络错误，请检查后端服务')
      console.error('重置数据失败:', err)
    } finally {
      setLoading(false)
    }
  }

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      addTodo()
    }
  }

  const handleEditKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      saveEdit()
    } else if (e.key === 'Escape') {
      cancelEdit()
    }
  }

  // 清除错误
  const clearError = () => setError(null)

  // 处理拖拽结束
  const handleDragEnd = async (event: DragEndEvent) => {
    const { active, over } = event
    setIsDragging(false)

    if (!over || active.id === over.id) {
      return
    }

    const oldIndex = todos.findIndex(todo => todo.id === active.id)
    const newIndex = todos.findIndex(todo => todo.id === over.id)

    if (oldIndex === -1 || newIndex === -1) {
      return
    }

    // 本地更新排序
    const newTodos = arrayMove(todos, oldIndex, newIndex)
    setTodos(newTodos)

    try {
      // 生成排序更新数据
      const orderUpdates: TodoReorderItem[] = newTodos.map((todo, index) => ({
        id: todo.id,
        order: index
      }))

      // 发送到后端
      const response = await todoApi.reorder(orderUpdates)
      if (!response.success) {
        setError(response.message || '更新排序失败')
        // 如果失败，恢复原顺序
        await loadTodos()
      }
    } catch (err) {
      setError('网络错误，请检查后端服务')
      console.error('更新排序失败:', err)
      // 如果失败，恢复原顺序
      await loadTodos()
    }
  }

  // 处理拖拽开始
  const handleDragStart = () => {
    setIsDragging(true)
  }

  return (
    <div className="max-w-4xl mx-auto px-4">
      {/* 错误提示 */}
      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6 flex items-center justify-between">
          <div className="flex items-center">
            <AlertCircle size={20} className="mr-2" />
            <span>{error}</span>
          </div>
          <button
            onClick={clearError}
            className="text-red-700 hover:text-red-900"
          >
            <X size={16} />
          </button>
        </div>
      )}

      {/* 欢迎消息 */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <div className="text-center">
          <h2 className="text-2xl font-semibold text-gray-700 mb-2">我的待办事项</h2>
          <p className="text-gray-500">
            管理您的个人任务，支持拖拽排序。您可以添加、编辑、删除和标记任务状态。
          </p>
          <div className="mt-4 flex justify-center gap-4">
            <button
              onClick={() => loadTodos()}
              disabled={loading}
              className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300"
            >
              <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
              刷新数据
            </button>
            <button
              onClick={resetData}
              disabled={loading}
              className="flex items-center gap-2 px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 disabled:bg-gray-300"
            >
              重置数据
            </button>
          </div>
        </div>
      </div>

      {/* 过滤器 */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <div className="flex flex-wrap gap-4 items-center">
          <div className="flex items-center gap-2">
            <Filter size={20} className="text-gray-500" />
            <span className="font-medium text-gray-700">过滤条件:</span>
          </div>
            
          <div className="flex items-center gap-2">
            <label className="text-sm text-gray-600">状态:</label>
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value as TodoStatus | 'all')}
              className="px-3 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">全部状态</option>
              <option value={TodoStatus.PENDING}>待处理</option>
              <option value={TodoStatus.IN_PROGRESS}>进行中</option>
              <option value={TodoStatus.COMPLETED}>已完成</option>
            </select>
          </div>
            
          <div className="flex items-center gap-2">
            <label className="text-sm text-gray-600">优先级:</label>
            <select
              value={filterPriority}
              onChange={(e) => setFilterPriority(e.target.value as TodoPriority | 'all')}
              className="px-3 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">全部优先级</option>
              <option value={TodoPriority.LOW}>低优先级</option>
              <option value={TodoPriority.MEDIUM}>中优先级</option>
              <option value={TodoPriority.HIGH}>高优先级</option>
            </select>
          </div>
        </div>
      </div>

      {/* 添加任务表单 */}
      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h3 className="text-lg font-semibold text-gray-700 mb-4">添加新任务</h3>
        <div className="space-y-4">
          <div className="flex gap-3">
            <input
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="请输入任务标题..."
              className="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
            <select
              value={inputPriority}
              onChange={(e) => setInputPriority(e.target.value as TodoPriority)}
              className="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value={TodoPriority.LOW}>低优先级</option>
              <option value={TodoPriority.MEDIUM}>中优先级</option>
              <option value={TodoPriority.HIGH}>高优先级</option>
            </select>
            <button
              onClick={addTodo}
              disabled={!inputValue.trim() || loading}
              className="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors duration-200 flex items-center gap-2"
            >
              <Plus size={20} />
              添加
            </button>
          </div>
          <textarea
            value={inputDescription}
            onChange={(e) => setInputDescription(e.target.value)}
            placeholder="任务描述（可选）..."
            rows={2}
            className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
          />
        </div>
      </div>

      {/* 任务统计 */}
      {stats && (
        <div className="bg-white rounded-lg shadow-md p-4 mb-6">
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4 text-center">
            <div>
              <div className="text-2xl font-bold text-blue-500">{stats.total}</div>
              <div className="text-sm text-gray-500">总任务</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-green-500">{stats.by_status.completed}</div>
              <div className="text-sm text-gray-500">已完成</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-orange-500">{stats.by_status.pending}</div>
              <div className="text-sm text-gray-500">待处理</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-blue-500">{stats.by_status.in_progress}</div>
              <div className="text-sm text-gray-500">进行中</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-red-500">{stats.by_priority.high}</div>
              <div className="text-sm text-gray-500">高优先级</div>
            </div>
          </div>
        </div>
      )}

      {/* 加载状态 */}
      {loading && (
        <div className="bg-white rounded-lg shadow-md p-8 text-center">
          <RefreshCw size={32} className="animate-spin mx-auto mb-4 text-blue-500" />
          <p className="text-gray-500">正在加载待办事项...</p>
        </div>
      )}

      {/* 任务列表 */}
      {!loading && (
        <div className="bg-white rounded-lg shadow-md overflow-hidden">
          {todos.length === 0 ? (
            <div className="p-8 text-center text-gray-500">
              <div className="text-6xl mb-4">📝</div>
              <p className="text-lg">
                {filterStatus !== 'all' || filterPriority !== 'all'
                  ? '没有符合筛选条件的任务'
                  : '还没有任务，快来添加第一个吧！'
                }
              </p>
            </div>
          ) : (
            <DndContext 
              sensors={sensors}
              collisionDetection={closestCenter}
              onDragStart={handleDragStart}
              onDragEnd={handleDragEnd}
            >
              <SortableContext 
                items={todos.map(todo => todo.id)}
                strategy={verticalListSortingStrategy}
              >
                {todos.map((todo) => (
                  <SortableTodoItem
                    key={todo.id}
                    todo={todo}
                    isEditing={editingId === todo.id}
                    editingData={editingData}
                    onStartEdit={startEdit}
                    onSaveEdit={saveEdit}
                    onCancelEdit={cancelEdit}
                    onToggleComplete={toggleComplete}
                    onDelete={deleteTodo}
                    onEditingDataChange={setEditingData}
                    onEditKeyPress={handleEditKeyPress}
                  />
                ))}
              </SortableContext>
            </DndContext>
          )}
        </div>
      )}

      {/* 底部提示 */}
      {!loading && todos.length > 0 && (
        <div className="mt-6 text-center text-sm text-gray-500">
          💡 提示: 点击任务前的圆圈可以快速标记完成状态，拖拽左侧手柄可以调整任务顺序，点击编辑按钮可以修改任务详情
        </div>
      )}
    </div>
  )
}